package com.tuling.vipes.service.impl;


import com.tuling.vipes.service.ElasticsearchSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.IndexedObjectInformation;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @创建人: Mhh
 * @创建时间: 2021/12/10
 * @描述: 新增
 */
@Service
public class ElasticsearchSaveServiceImp implements ElasticsearchSaveService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    /**
     * @param classType : 要创建es的索引及映射(一定要通过这种方法创建，否则都是创建出来的映射都是默认的)基于传入对象中的@Document注解
     * @return boolean
     * @throws
     * @Author Mhh
     * @Date 2021/12/9 10:43
     */
    @Override
    public boolean createIndexAndMapping(Class<?> classType) {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(classType);
        if (indexOperations.exists())
            return true;
        boolean index = indexOperations.create();
        boolean mapping = indexOperations.putMapping(classType);
        return index && mapping;
    }


    /**
     * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T，集合Iterable<T>，可变参 T... 】
     * @return T  反参对象
     * @explain : 添加文档
     * @Author Mhh
     * @Date 2021/12/27 10:55
     */
    @Override
    public <T> Iterable<T> save(Iterable<T> entities) {
        return elasticsearchRestTemplate.save(entities);

    }


    /**
     * @param t : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T，集合Iterable<T>，可变参 T... 】
     * @return T  反参对象
     * @explain : 添加文档
     * @Author Mhh
     * @Date 2021/12/27 10:55
     */

    @Override
    public <T> T save(T t) {
        return elasticsearchRestTemplate.save(t);
    }

    public <T> T batchSave(List<T> list, Class<?> classType) {
        List<IndexQuery> queryList = new ArrayList<>();
        for (T t : list) {
//            IndexQuery indexQuery = new IndexQuery();
//            indexQuery.setId(employee.getId().toString());
//            String json =
//            indexQuery.setSource(json);
//            queries.add(indexQuery);
        }
        List<IndexedObjectInformation> indexedObjectInformations = elasticsearchRestTemplate.bulkIndex(queryList, classType);

        return null;
    }
}
